#include "elk_preview_view.h"
#include "ui_elk_preview_view.h"

ElkPreviewView::ElkPreviewView(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ElkPreviewView)
{
    ui->setupUi(this);
}

ElkPreviewView::~ElkPreviewView()
{
    delete ui;
}

void ElkPreviewView::bind(QWeakPointer<ElkWebDelegate> delegate)
{
    if (!delegate_) {
        delegate_ = delegate;

        connect(delegate_.data(), SIGNAL(pageSourceVisited(const QString &,
                                                           const QString &)),
                this, SLOT(onPageSourceVisited(const QString &,
                                               const QString &)));
        connect(delegate_.data(), SIGNAL(displayTextVisited(const QString &,
                                                            const QString &)),
                this, SLOT(onDisplayTextVisited(const QString &,
                                                const QString &)));
    }
}

void ElkPreviewView::display(const QString &frame, const QString &plainText)
{
    Q_UNUSED(frame);
    ui->textEdit->clear();
    QStringList list = plainText.split(QRegExp("[\r\n]"), QString::SkipEmptyParts);
    for (auto text : list) {
        ui->textEdit->append(text);
    }
}

void ElkPreviewView::displayPageSource(const QString &frame, const QString &source)
{
    Q_UNUSED(frame);
    ui->textEdit->setPlainText(source);
}

void ElkPreviewView::onPageSourceVisited(const QString &frame, const QString &source)
{
    displayPageSource(frame, source);
}

void ElkPreviewView::onDisplayTextVisited(const QString &frame, const QString &text)
{
    display(frame, text);
}

void ElkPreviewView::on_pushButtonClear_clicked()
{
    ui->textEdit->clear();
}

void ElkPreviewView::on_pushButtonSave_clicked()
{

}
